Trait

Traits in Scala have a lot of similarities with interfaces in Java, but a trait is more powerful than an interface because it allows developers to implement members within it. A trait is like an interface with a partial implementation. Scala traits consist of method and field definition that can be reused by mixing classes. The classes can mix any number of traits. 
  • In scala, trait is a collection of abstract and non-abstract methods. 
  • You can create trait that can have all abstract methods or some abstract and some non-abstract methods. 
  • A variable that is declared either by using val or var keyword in a trait get internally implemented in the class that implements the trait. 
  • Any variable which is declared by using val or var but not initialized is considered abstract.
  • Traits are compiled into Java interfaces with corresponding implementation classes that hold any methods implemented in the traits.
  • Trait can not be instantiated, thus it has no parameters
  • Although a trait can extend only one class, but a class can have multiple traits.
Scala trait Syntax         
trait trait_name{
// Variables
//Method
}
As discussed in the introduction, the Scala Traits are inherited by a class using the extends keyword.

class Scala_Tutorial extends DataCamp{
// Variables
// Methods
}
 
trait myTrait{
def scala()
}

class myClass extends myTrait{
def scala(){
println("This class extends myTraits")
}
}

object demo{
def main(args:Array[String]){
var obj = new myClass()
obj.scala()
}
}
Trait With abstract method
trait MyTrait
{
def pet
def pet_color
}

class MyClass extends MyTrait
{
def pet()
{
println("Pet: Dog")
}
def pet_color()
{
println("Pet_color: White")
}
def pet_name()
{
println("Pet_name: Dollar")
}
}

object demo {

def main(args: Array[String]) {
val obj = new MyClass();
obj.pet();
obj.pet_color();
obj.pet_name();
}
}
In Scala we are allowed to implement the method (only abstract methods) in traits.if trait contain method implementation, then the class which extends this trait need not implement the method which already implemented in a trait.

Trait with abstract and non-abstract methods.
trait MyTrait
{
def greeting
def tutorial
{
println("This is a tutorial" + "of Traits in Scala")
}
}

class MyClass extends MyTrait
{
// Implementation of abstract method
// No need to implement a non-abstract
// method because it already implemented
def greeting()
{
println("Trait with abstract and non abstract method")
}
}

object demo
{
def main(args: Array[String])
{
val obj = new MyClass();
obj.greeting
obj.tutorial
}
}
  • Traits does not contain constructor parameters.
  • Where a class inherits one trait then use extends keywords.
  • When class inherits multiple  traits then use extend keywords before the first trait and after that use with keyword before other traits.
trait BMW{
// trait variables
var make: String = "BMW"
var model: String = "X7"
var fuel: Int = 40

// trait method: NON-ABSTRACT
def Display()
{
println("Make of the Car : " + make);
println("Model of the Car : " + model);
println("Fuel capacity of the Car : " + fuel);
}
}


class Car extends BMW{
// class variables
var make1: String = "Mercedes Benz"
var model1: String = "S350D"
var fuel1: Int = 50

// Class method
def Merc_Specs()
{
println("Make of the Car : " + make1);
println("Model of the Car : " + model1);
println("Fuel capacity of the Car : " + fuel1);
}
}

object demo
{
// Main method
def main(args: Array[String])
{
// Class object
var obj = new Car();
println("Calling the Class Method")
obj.Merc_Specs();
println("Calling the Trait Method")
obj.Display();
}
}
 
trait mytrait{
def scala()
}

class myClass extends Scala_Course{
def print(){
println("Error: Class DataCamp needs to be Abstract")
}
}

object demo{
def main(args:Array[String]){
var obj = new DataCamp()
obj.print()
}
}
class Class_Name extends Trait_Name1 with Trait_Name2 with Trait_Name3{
// Code..
}

trait myTrait1
{   
    def greeting
}
trait myTrait2
{   
    def tutorial
    {
        println("This is a tutorial" + " of Traits in Scala")
    }
}

class myclass extends myTrait1 with myTrait2
{
 // Implementation of abstract method
    def greeting()
    {
        println("Welcome to Scala Tutorials")
    }
}

object traits1 {
def main(args: Array[String])
 {
  var obj= new myclass();
      obj.greeting
      obj.tutorial
}
}

If a class extends a trait but does not implement the members declared in that trait, it must be declared abstract. Let's see an example.
trait Printable{
def print()
}

abstract class A4 extends Printable{ // Must declared as abstract class
def printA4(){
println("Hello, this is A4 Sheet")
}
}

class A5 extends A4{
def print{
println("hello")
}
}

object demo{
def main(args:Array[String]){
val obj=new A5
obj.print
obj.printA4
}
}

Scala Trait Example: Implementing Multiple Traits in a Class
If a class implements multiple traits, it will extend the first trait, class, abstract class. with keyword is used to extend rest of the traits.
You can achieve multiple inheritances by using trait.
trait Printable{
def print()
}
trait Showable{
def show()
}
class myClass extends Printable with Showable{
def print(){
println("This is printable")
}
def show(){
println("This is showable");
}
}

object demo{
def main(args:Array[String]){
var a = new myClass()
a.print()
a.show()
}
}

 

No comments:

Post a Comment